package com.faceCaptor.main;

import com.alibaba.fastjson.JSONObject;
import com.faceCaptor.entity.Remark;
import com.faceCaptor.model.UserModel;
import com.faceCaptor.util.HttpUtil;
import com.ha.facecamera.configserver.ConfigServer;
import com.ha.facecamera.configserver.pojo.Face;
import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;

import java.io.ByteArrayOutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ConfirmMessageDialog extends Dialog {

	private Map<String, String> map;
	private Image fImg;
	private byte[] imgData;
	private Logger log = Logger.getLogger(ConfirmMessageDialog.class);

	public ConfirmMessageDialog(Shell parentShell, Map<String, String> map, Image fImg) {
		super(parentShell);
		this.map = map;
		this.fImg = fImg;
	}
	public ConfirmMessageDialog(Shell parentShell, Map<String, String> map, Image fImg, byte[] imgData) {
		super(parentShell);
		this.map = map;
		this.fImg = fImg;
		this.imgData = imgData;
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		Composite container = (Composite) super.createDialogArea(parent);
		container.setSize(450, 714);
		container.setLayout(new FormLayout());
		Color color = Display.getCurrent().getSystemColor(SWT.BACKGROUND);
		container.setForeground(color);


		CLabel label1 = new CLabel(container, SWT.NONE);
		label1.setAlignment(SWT.CENTER);
		label1.setText("确认客户信息");
		FormData fdata = new FormData();
		fdata.left = new FormAttachment(0, 5);
		fdata.right = new FormAttachment(100, -5);
		fdata.top = new FormAttachment(0, 5);
		fdata.bottom = new FormAttachment(10, -5);
		label1.setLayoutData(fdata);
		// formToolkit.adapt(label1);

		Label img = new Label(container, SWT.HORIZONTAL);
		// GridData data = new GridData(200,200);
		// img.setLayoutData(new FormData(200,200));
		img.setAlignment(SWT.CENTER);
		img.setImage(fImg);
		// img.setImage(SWTResourceManager.getImage(ConfirmMessageDialog.class,
		// "/images/star.gif"));

		final FormData labelData = new FormData(SWT.DEFAULT, SWT.DEFAULT);
		labelData.left = new FormAttachment(0, 0);
		labelData.right = new FormAttachment(100, 0);
		labelData.top = new FormAttachment(label1, 0);
		img.setLayoutData(labelData);

		Composite composite1 = new Composite(container, SWT.NONE);
		FormData labelData1 = new FormData(SWT.DEFAULT, SWT.DEFAULT);
		labelData1.left = new FormAttachment(0, 0);
		labelData1.right = new FormAttachment(100, 0);
		labelData1.top = new FormAttachment(img, 0);
		composite1.setLayoutData(labelData1);
		RowLayout rowLayout = new RowLayout(SWT.VERTICAL);
		rowLayout.wrap = true;
		rowLayout.fill = false;
		rowLayout.justify = true;
		rowLayout.marginLeft = 10;
		// rowLayout.marginTop = 100;
		rowLayout.marginRight = 10;
		rowLayout.marginBottom = 10;
		rowLayout.spacing = 0;
		composite1.setLayout(rowLayout);

		Label nameLabel = new Label(composite1, SWT.HORIZONTAL);
//		System.out.println("客户姓名：");
		if (map.get("username") != null) {
			nameLabel.setText("客户姓名：" + map.get("username"));
		} else {
			nameLabel.setText("客户姓名：");
		}

		Label label2 = new Label(composite1, SWT.NONE);
		if (map.get("type") != null) {
			label2.setText("客户类型：" + map.get("type"));
		} else {
			label2.setText("客户类型：");
		}

		Label label3 = new Label(composite1, SWT.NONE);
		if (map.get("group") != null) {
			label3.setText("客户群体：" + map.get("group"));
		} else {
			label3.setText("客户群体：");
		}

		Label label4 = new Label(composite1, SWT.NONE);
		if (map.get("creator") != null) {
			label4.setText("店员：" + map.get("creator"));
		} else {
			label4.setText("店员：");
		}

		Label label5 = new Label(composite1, SWT.NONE);
		if (map.get("detail") != null) {
			label5.setText("到访信息：" + map.get("detail"));
		} else {
			label5.setText("到访信息：");
		}

		return container;
	}

	// override method to use "Login" as label for the OK button
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, "确认", true);
		createButton(parent, IDialogConstants.CANCEL_ID, "取消", false);
	}

	@Override
	protected Point getInitialSize() {
		return new Point(450, 714);
	}

	@Override
	protected Point getInitialLocation(Point initialSize) {
		Point location = new Point(this.getParentShell().getLocation().x + 150,
				this.getParentShell().getLocation().y + 140);
		return location;
	}

	@Override
	protected void okPressed() {
		Map<String, String> employeeMap = (Map<String, String>) MainView.cachedmap.get("employee");
		try {
//			System.out.println(map.toString());
			if(map.containsKey("userId")){

//				System.out.println("老会员提交备注");
				Remark remark =new Remark();
				remark.setCreateTime(new Timestamp(new Date().getTime()));
				remark.setDetail(map.get("detail"));
				remark.setUserId(map.get("userId"));
				remark.setCreator(employeeMap.get(map.get("creator")));
				remark.setUpdateTime(new Timestamp(new Date().getTime()));

				JSONObject jsonObject = HttpUtil.postSwtForm(HttpUtil.HOST + HttpUtil.UPDATEUSER, map);
				JSONObject jsonObject2=HttpUtil.postSwtForm(HttpUtil.HOST+HttpUtil.ADDREMARK, remark);
				Thread.sleep(1000);

				if (jsonObject2.get("code").equals("101")) {
//					System.out.println("添加备注成功");
					log.info("添加备注成功");
					MessageDialog.openInformation(getShell(), "提示", "添加备注成功");
				} else {
//					System.out.println("添加备注失败");
					log.error("添加备注失败:" + remark);
					MessageDialog.openError(getShell(), "提示", "添加备注失败");
				}
			}else{

				Map cache = MainView.cachedmap;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				ImageLoader imageLoader = new ImageLoader();
				imageLoader.data = new ImageData[] { fImg.getImageData() };
				imageLoader.save(baos, fImg.type);
				baos.close();


				byte[] featureImageData = baos.toByteArray();
				List<ConfigServer> configServerList=(List<ConfigServer>) cache.get("configServerList");

				AddFaceDialog dialog = new AddFaceDialog();
				Face face = new Face();
				for(ConfigServer configServer : configServerList) {
					String id = face.getId();
					if (id == null) {
						if (imgData != null) {
							face = dialog.addFaceFromCaptureData(configServer, "0216", imgData, null);
						} else {
							face = dialog.addFaceFromCaptureData(configServer, "0216", featureImageData, null);
						}
					} else{
						if (imgData != null) {
							face = dialog.addFaceFromCaptureData(configServer, "0216", imgData, id);
						} else {
							face = dialog.addFaceFromCaptureData(configServer, "0216", featureImageData, id);
						}
					}

					if (face == null) {
//						System.out.println("注册失败");
						log.error("注册人脸失败");
						String errorMsg =configServer.getLastErrorMsg();
						if(errorMsg.indexOf("(")!=-1){
							MessageDialog.openError(getShell(), "提示", errorMsg.substring(errorMsg.lastIndexOf("(")+1,errorMsg.lastIndexOf(")")));
						}else{
							MessageDialog.openError(getShell(), "提示", errorMsg);
						}
					}
				}
				if (face != null) {
					UserModel userModel = new UserModel();
					userModel.setFeatureImageData(featureImageData);
					userModel.setUserId(face.getId());
					userModel.setUsername(map.get("username"));
					userModel.setMobilephone(map.get("mobilephone"));
					userModel.setType(map.get("type"));
					userModel.setGroup(map.get("group"));
					userModel.setDetail(map.get("detail"));
					userModel.setShopId((String)cache.get("shopId"));
					userModel.setCreator(employeeMap.get(map.get("creator")));
					userModel.setVisitCount(1);

					JSONObject jsonObject = HttpUtil.postSwtForm(HttpUtil.HOST + HttpUtil.ADDUSER, userModel);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
//					System.out.println(jsonObject);
					if (jsonObject.get("code").equals("101")) {
//						System.out.println("保存个人信息成功");
						log.info("保存个人信息成功");
						MessageDialog.openInformation(getShell(), "提示", "保存个人信息成功");
					} else {
//						System.out.println("保存个人信息失败");
						log.error("保存个人信息失败:" + userModel);
						MessageDialog.openError(getShell(), "提示", "保存个人信息失败");
					}

				}
			}
			super.okPressed();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
//			System.out.println("父窗口关闭");

		}



	}



}
